package com.example.weather;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.gson.Gson;

import java.io.IOException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by 古嘉华 on 2018/5/1.
 */

public class CxFragment extends android.support.v4.app.Fragment {

        private View mTestView;
        private RecyclerView recyclerView;
        private RecyclerWeatherAdapter recyclerWeatherAdapter;
        private ImageView ivNowInfo;
        private TextView tvNowInfo;
        private EditText edtCity;
        private Button btnSearch;
        private WeatherData weatherData;
        private ArrayList<String> data = new ArrayList<>();
        private ArrayList<Integer> imgData = new ArrayList<>();
        private List<WeatherData.DataBean.ForecastBean> forecast;
        private Handler handler;
        private String result;
        private static final int GET_WEB_SUCCESS = 1001;
        private TempratureView tempratureView;

        @Nullable
        @Override
        public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
            mTestView = inflater.inflate(R.layout.layout2, container, false);
            edtCity = mTestView.findViewById(R.id.edt_city);
            btnSearch = mTestView.findViewById(R.id.btn_search);
            ivNowInfo = mTestView.findViewById(R.id.ivNowInfo);
            tvNowInfo = mTestView.findViewById(R.id.tvNowInfo);
            recyclerView = mTestView.findViewById(R.id.recycler_view);
//        Log.e("onCreateView:","hua");
            initHandle();
            getUseokHttp();
            tempratureView = mTestView.findViewById(R.id.tem_view);
//        setUseData();
            initData();
            return mTestView;
        }

        private void getUseokHttp() {
            btnSearch.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    data.clear();
                    imgData.clear();
                    String city = edtCity.getText().toString();
                    String url = "https://www.sojson.com/open/api/weather/json.shtml?city=" + URLEncoder.encode(city);
                    Log.e("Button:","msg:"+city);
                    OkHttpClient okHttpClient = new OkHttpClient();
                    Request request = new Request.Builder().url(url).build();
                    Call call = okHttpClient.newCall(request);
                    call.enqueue(new Callback() {
                        @Override
                        public void onFailure(Call call, IOException e) {
                            Log.e("MainActivity",e.toString());
                        }

                        @Override
                        public void onResponse(Call call, Response response) throws IOException {
//                Log.e("msg:","json:"+response.body().string());
                            Message message = Message.obtain();
                            message.what = GET_WEB_SUCCESS;
                            message.obj = response.body().string();
                            handler.sendMessage(message);
                        }
                    });
                }
            });
//            更新自定义View
//            RefreshView();
        }

/*    private void RefreshView() {
        class GameThread implements Runnable {
            public void run() {
                while (!Thread.currentThread().isInterrupted()) {
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        Thread.currentThread().interrupt();
                    }

                    // 使用postInvalidate可以直接在线程中更新界面
                    TempratureView.postInvalidate();
                }
            }
        }
    }*/

    private void initHandle() {
            handler = new Handler(new Handler.Callback() {
                @Override
                public boolean handleMessage(Message message) {
                    if(message.what == GET_WEB_SUCCESS){
                        result = (String) message.obj;
//                    Log.e("initHandle:","hihi");
                        setUseData();
                    }
                    return false;
                }
            });
        }

        private void setUseData() {
            try {
                if(result!=null) {
                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年MM月dd日");// HH:mm:ss
                    //获取当前时间
                    Date date = new Date(System.currentTimeMillis());
//                Log.e("msg","Date:"+simpleDateFormat.format(date));
                    weatherData = new Gson().fromJson(result, WeatherData.class);
                    forecast = weatherData.getData().getForecast();
                    StringBuffer buffer = new StringBuffer();
                    buffer.append("城市: ").append(weatherData.getCity());
                    buffer.append("\n日期: ").append(simpleDateFormat.format(date));
                    buffer.append("\n湿度: ").append(weatherData.getData().getShidu());
                    buffer.append("\nPm25: ").append(weatherData.getData().getPm25());
                    buffer.append("\n风向: ").append(forecast.get(0).getFx());
                    buffer.append("\n天气状况: ").append(forecast.get(0).getType());
                    buffer.append("\n温馨提示: ").append(forecast.get(0).getNotice());
                    //        Log.e("msg","Data:"+buffer.toString());
                    ivNowInfo.setImageResource(getWeatherImage(forecast.get(0).getType()));
                    tvNowInfo.setText(buffer.toString());
                    tempratureView.setData(forecast);
//                    Log.e("forecast:","msg:"+forecast);
//                int date = Integer.parseInt(forecast.get(0).getDate().substring(0, 2));
                    //        Log.e("msg","Data:"+date);
                    //            data = new ArrayList<>();
                    //            imgData = new ArrayList<>();
                    for (int i = 0; i < forecast.size(); i++) {
                        int wendu=(Integer.parseInt(forecast.get(i).getHigh().substring(3,5)) + Integer.parseInt(forecast.get(i).getLow().substring(3,5)))/2;
//                    Log.e("msg","Data:"+wendu);
                        StringBuffer buffer1 = new StringBuffer();
                        buffer1.append(forecast.get(i).getType());
                        buffer1.append("\n").append(forecast.get(i).getDate());
                        buffer1.append("\n平均温度: ").append(wendu).append("℃");
                        buffer1.append("\n").append(forecast.get(i).getFx());
                        //            Log.e("msg","Data:"+buffer1);
                        data.add(buffer1.toString());
                        imgData.add(getWeatherImage(forecast.get(i).getType()));
                    }
                }else {

                    tvNowInfo.setText("无数据");
                    String temp = "无数据";
                    for (int i = 0; i < 5; i++) {
                        //            Log.e("msg","Data:"+buffer1);
                        data.add(i+temp);
                        imgData.add(R.mipmap.ic_launcher);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
//        Log.e("msg","Data:"+getWeatherImage(forecast.get(0).getType()));
            initData();
        }

        private void initData() {
            LinearLayoutManager layoutManager = new LinearLayoutManager(this.getActivity(),LinearLayoutManager.HORIZONTAL,false);
//        layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
            // 设置布局管理器
            recyclerView.setLayoutManager(layoutManager);
//        recyclerView.setLayoutManager(new LinearLayoutManager(this));
            // 设置adapter
            recyclerWeatherAdapter = new RecyclerWeatherAdapter(this.getActivity(),data,imgData);
            recyclerView.setAdapter(recyclerWeatherAdapter);
        }

  /*  private void initWeatherImg() {
        List<WeatherData.DataBean.ForecastBean> forecast = weatherData.getData().getForecast();

        ivWeather_a.setImageResource(getWeatherImage(forecast.get(0).getType()));
        ivWeather_b.setImageResource(getWeatherImage(forecast.get(1).getType()));
        ivWeather_c.setImageResource(getWeatherImage(forecast.get(2).getType()));
        ivWeather_d.setImageResource(getWeatherImage(forecast.get(3).getType()));
        ivWeather_e.setImageResource(getWeatherImage(forecast.get(4).getType()));
    }*/

        private int getWeatherImage(String type) {
            if(type.equals("晴")){
                return R.drawable.sun;
            }else if(type.equals("阵雨")){
                return R.drawable.thunderstorm;
            }else if(type.equals("中雨")){
                return R.drawable.rain;
            }else if(type.equals("小雨")){
                return R.drawable.rain;
            }else if(type.equals("大雨")){
                return R.drawable.rain;
            }else if(type.equals("雷阵雨")){
                return R.drawable.thunder;
            }else if(type.equals("多云")){
                return R.drawable.cloudy;
            }else if(type.equals("阴")){
                return R.drawable.overcast;
            }
            return R.drawable.sunny;
        }
    }

